<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/3/27
 * Time: 9:34
 */
namespace api\modules\shop\controllers;

//use yii\web\Controller;
use common\models\Activity;
use common\models\ActivityAttr;
use common\models\Order;
use common\models\Shop;
use common\service\CommonService;
use common\service\ConstantService;
use common\service\GlobalUrlService;
use common\models\Googs;
use common\models\GoogsAttr;
use common\service\WechatService;

class ActivityController extends ShopBaseController{

    //数据中心
    public function actionIndex(){

        $start_time = strtotime(date('Y-m-d ') . '00:00:00');
        $end_time = strtotime(date('Y-m-d ') . '23:59:59');
        //需要统计的数据
        //1 日,总订单数
        $order_query = Order::find();
        $max_time = ['>=', 'created_time', $start_time];
        $min_time = ['<=', 'created_time', $end_time];
        $pay_status = ['=', 'pay_status', 1];
        $shop_ids = ['=', 'shop_id', $this->shop['id']];
        $noeq = ['!=', 'order_status', 6];
        $day_order = $order_query->select('count(id) as day_order_count')
            ->andWhere($max_time)
            ->andWhere($min_time)
            ->andWhere($pay_status)
            ->andWhere($shop_ids)
            ->andWhere(['>=', 'order_status', 1])
            ->asArray()
            ->one();
        $count_order = Order::find()->select('count(id) as order_count')
            ->andWhere($pay_status)
            ->andWhere($shop_ids)
            ->andWhere(['>=', 'order_status', 1])
            ->asArray()
            ->one();

        //2. 日,总商品销量 算法: 已完成
        $count_goods = Order::find()->select('sum(goods_num) as goods_count')
            ->andWhere($pay_status)
            ->andWhere($shop_ids)
            ->andWhere($noeq)
            ->asArray()
            ->one();
        //3 日,总销售金额 算法:已完成
        //日销售金额
        $day_money_ywc = $order_query->select('sum(order_money) as day_money_count')
            ->andWhere($max_time)
            ->andWhere($min_time)
            ->andWhere($pay_status)
            ->andWhere($noeq)
            ->andWhere($shop_ids)
            ->asArray()
            ->one();
        //总销售金额
        $count_money_ywc = Order::find()->select('sum(order_money) as money_count')
            ->andWhere($pay_status)
            ->andWhere($noeq)
            ->andWhere($shop_ids)
            ->asArray()
            ->one();
        //4. 退款订单
        $order_status_4 = Order::find()->select('count(id) as count_order')
            ->where(['shop_id'=>$this->shop['id'],'order_status'=>4,'is_delete'=>0])->asArray()->one();
        //5. 待发货订单
        $order_status_1 = Order::find()->select('count(id) as count_order')
            ->where(['shop_id'=>$this->shop['id'],'order_status'=>1])->asArray()->one();
        //店铺logo
        $shop=Shop::find()->where(['id'=>$this->shop['id']])->one();
        $shop_logo=GlobalUrlService::buildCdnUrl($shop['shop_logo']);

        //店铺名称
        $shop_name=$shop['shop_name'];

        $data_center = [
            'day_count' => $day_order['day_order_count'],
            'order_countAll' => $count_order['order_count'],
            'count_goods' => $count_goods['goods_count'],
            'money_totle' =>substr(sprintf("%.3f", $day_money_ywc['day_money_count']),0,-1),//round($day_money_ywc['day_money_count'],2),
            'money_totleAll' =>substr(sprintf("%.3f", $count_money_ywc['money_count']),0,-1),//round($count_money_ywc['money_count'],2),
            'tui_count' =>$order_status_4['count_order'],
            'dai_count' =>$order_status_1['count_order'],
            'shop_logo'=>$shop_logo,
            'shop_name'=>$shop_name
        ];

//        $shop_id = $this->shop['id'];
//        //店铺logo
//        $shop=Shop::find()->where(['id'=>$shop_id])->one();
//        $shop_logo=GlobalUrlService::buildCdnUrl($shop['shop_logo']);
//        //店铺名称
//        $shop_name=$shop['shop_name'];
//        //退款中订单数
//        $tui_count=Order::find()->where(['shop_id'=>$shop_id,'order_status'=>4])->count();
//
//        //代发货订单数
//        $dai_count=Order::find()->where(['shop_id'=>$shop_id,'order_status'=>1])->count();
//
//        //日订单数
//            //当天的零点的时间戳
//            $time_one = strtotime(date('Ymd'));
//            // 获得今天24点的时间戳
//            $time_two = strtotime(date('Ymd')) + 86400;
//            //var_dump(time());var_dump($time_two);exit();
//        $query=Order::find();
//        $query->andWhere(['>=','pay_time',$time_one]);
//        $query->andWhere(['<=','pay_time',$time_two]);
//        $query->andWhere(['shop_id'=>$shop_id]);
//        $query->andWhere(['pay_status'=>1]);
//        $day_count=$query->count();
//
//        //当天已退款金额
//        $tui_one=Order::find();
//        $tui_one->andWhere(['>=','pay_time',$time_one]);
//        $tui_one->andWhere(['<=','pay_time',$time_two]);
//        $tui_one->andWhere(['shop_id'=>$shop_id]);
//        $tui_one->andWhere(['pay_status'=>6]);
//        $money_tui_one=$query->sum('order_money');
//        //日销售金额
////        $money_totle = $tui_one->select('sum(order_money) as day_money_count')
////            ->andWhere($time_one)
////            ->andWhere($time_two)
////            ->andWhere(['=', 'pay_status', 1])
////            ->andWhere(['!=', 'order_status', 6])
////            ->andWhere(['shop_id'=>$shop_id])
////            ->asArray()
////            ->one();
////        //日销售总金额
//        $money_totle=$query->sum('order_money')-$money_tui_one;
////
//        $query_totle=Order::find();
////        $query_totle->andWhere(['shop_id'=>$shop_id]);
////        $query_totle->andWhere(['pay_status'=>1]);
//        //总订单数
//        $order_countAll=$query_totle->count();
////        $money_totleAll = Order::find()->select('sum(order_money) as money_count')
////            ->andWhere(['=', 'pay_status', 1])
////            ->andWhere(['!=', 'order_status', 6])
////            ->andWhere(['shop_id'=>$shop_id])
////            ->asArray()
////            ->one();
////        //总销售金额
//        $money_totleAll=$query_totle->sum('order_money');
//        if ($money_totleAll==null){
//            $money_totleAll=0;
//        }
//
//
//        //数据汇总
//        $data_center['tui_count']=$tui_count;
//        $data_center['dai_count']=$dai_count;
//        $data_center['day_count']=$day_count;
//        $data_center['money_totle']=round($money_totle,2);//floor($money_totle*100)/100;
//        $data_center['shop_logo']=$shop_logo;
//        $data_center['order_countAll']=$order_countAll;
//        $data_center['money_totleAll']=round($money_totleAll,2);//floor($money_totleAll*100)/100;
//        $data_center['shop_name']=$shop_name;
//        //return $this->renderJson(['tui_count'=>$tui_count,'dai_count'=>$dai_count,'day_count'=>$day_count,'money_totle'=>$money_totle,'shop_logo'=>$shop_logo],'数据中心：tui_count退款中订单数，dai_count代发货订单数，day_count日订单数，money_totle日销售总金额,shop_logo店铺logo',ConstantService::$response_success);
        return $this->renderJson([$data_center],'数据中心：tui_count退款中订单数，dai_count代发货订单数，day_count日订单数，money_totle日销售总金额,shop_logo店铺logo',ConstantService::$response_success);
    }
    /*
     * 商家活动列表
     * */
    public function actionActivity(){
            $name=$this->post('name');
            $shop_id=$this->shop['id'];
            $ac_query = Activity::find();
            $ac_query->andWhere(['isdel'=>1]);
            $ac_query->andWhere(['shop_id'=>$shop_id]);
            if(!empty($name)){
                $ac_query->andWhere(['like','activity_name',$name]);
            }
            $p = intval( $this->post('page',1) );
            $p = ( $p > 0 )? $p : 1;
            $offset = ($p - 1) *  $this->page_size;
            $data_end1=$ac_query->limit( $this->page_size)->orderBy('creat_time desc')->offset($offset)->asArray()->all();
            foreach ($data_end1 as $value){
                if (intval($value['end_time'])<time()){
                    $attr_status=Activity::find()->where(['id'=>$value['id']])->one();
                    $attr_status['status']=2;
                    $attr_status->save();
                }
            }
            $data_end=$ac_query->limit( $this->page_size)->offset($offset)->asArray()->all();
            return $this->renderJson([$data_end,$name],'',ConstantService::$response_success);
    }

    /*
     * 单个开始活动
     * */
    public function actionBegin(){
        if ($this->isPost()){
            $id=$this->post('id');
            $data=Activity::find()->where(['id'=>$id])->one();
            $data['status']=1;
            $re=$data->save();
            if ($re){
                return $this->renderJson([],'激活成功',ConstantService::$response_success);
            }else{
                return $this->renderJson([],'激活失败',ConstantService::$response_fail);
            }
        }
    }

    /*
     * 开始全部活动
     * */
    public function actionBeginAll(){
       // if ($this->isPost()){
        $id = empty($this->shop['id'])?1:$this->shop['id'];
        $active_model = Activity::find();
        $active_model->select('id');
        $active_model->andWhere(['>','end_time',time()]);
        $active_model->andWhere(['<=','begin_time',time()]);
        $active_model->andWhere(['shop_id'=>$id]);
        $active_model->asArray();
        $data = $active_model->all();
        $aid = [];
        foreach ($data as $v){
            $aid[] = $v['id'];
        }
        if(Activity::updateAll(['status'=>1,'update_time'=>time()],['id'=>$aid])){
            return $this->renderJson([],'所有活动激活成功',ConstantService::$response_success);
        }else{
            return $this->renderJson([],'所有活动激活失败',ConstantService::$response_fail);
        }
       // }
    }

    /*
     * 暂定某一个活动
     */
    public function actionEnd(){
        if($this->isPost()){
            $id=$this->post('id');
            $data=Activity::find()->where(['id'=>$id])->one();
            $data['status']=0;
            $re=$data->save();
            if ($re){
                return $this->renderJson([],'暂停成功',ConstantService::$response_success);
            }else{
                return $this->renderJson([],'暂停失败',ConstantService::$response_fail);
            }
        }
    }

    /*
     *   暂停所有活动
     * */
    public function actionEndAll(){
        //if($this->isPost()){
        $id = empty($this->shop['id'])?1:$this->shop['id'];
        $active_model = Activity::find();
        $active_model->select('id');
        $active_model->andWhere(['>','end_time',time()]);
        $active_model->andWhere(['<=','begin_time',time()]);
        $active_model->andWhere(['shop_id'=>$id]);
        $active_model->asArray();
        $data = $active_model->all();
        $aid = [];
        foreach ($data as $v){
            $aid[] = $v['id'];
        }
        if(Activity::updateAll(['status'=>0,'update_time'=>time()],['id'=>$aid])){
            return $this->renderJson([],'所有活动暂停成功',ConstantService::$response_success);
        }else{
            return $this->renderJson([],'所有活动暂停失败',ConstantService::$response_fail);
        }
       // }
    }

    /*
     * 查案活动详情（活动列表页面点击“查看/编辑”）
     * */
    public function actionSelect(){
        if ($this->isPost()){
            $activity_id=$this->post('id');
            $activity=Activity::find()->where(['id'=>$activity_id])->one();
            $activity_attr=ActivityAttr::find()->where(['activity_id'=>$activity_id])->asArray()->all();
            //销量
            //返回$activity_attr数组中id单一列的值
            $attr_id=array_column($activity_attr,'id');
            $ord_count=Order::find()->select(['goods_attr_id','count(id) as order_salenum'])->andWhere([ 'pay_status'=>1])->andWhere( ['in','goods_attr_id',$attr_id])->groupBy('goods_attr_id')->asArray()->all();
            //将二维数组转换为一维数组
            $newordercount = [];
            foreach ( $ord_count as $val){
                $newordercount[$val['goods_attr_id']] = $val;
            }
            foreach ($activity_attr as &$item){
                $item['order_count'] = 0;
                foreach ($newordercount as $key=>$val){
                    if($item['id'] == $key){
                        $item['order_count'] = $newordercount[$key]['order_salenum'];
                    }
                }
            }
            return $this->renderJson(['activity'=>$activity,'activity_attr'=>$activity_attr],"查看成功",ConstantService::$response_success);
        }else{
            return $this->renderJson([],'请用正确的方式进入查看页面',ConstantService::$response_fail);
        }
    }

    /*
     * 加载活动修改页面
     * */
    public function actionUpdata(){
        if ($this->isPost()){
            $activity_id=$this->post('id');
            $activity=Activity::find()->where(['id'=>$activity_id])->one();
            $activity_attr=ActivityAttr::find()->where(['activity_id'=>$activity_id])->asArray()->all();
            //销量
            //返回$activity_attr数组中id单一列的值
            $attr_id=array_column($activity_attr,'id');
            $ord_count=Order::find()->select(['goods_attr_id','count(id) as order_salenum'])->andWhere([ 'pay_status'=>1])->andWhere( ['in','goods_attr_id',$attr_id])->groupBy('goods_attr_id')->asArray()->all();
            //将二维数组转换为一维数组
            $newordercount = [];
            foreach ( $ord_count as $val){
                $newordercount[$val['goods_attr_id']] = $val;
            }
            foreach ($activity_attr as &$item){
                $item['order_count'] = 0;
                foreach ($newordercount as $key=>$val){
                    if($item['id'] == $key){
                        $item['order_count'] = $newordercount[$key]['order_salenum'];
                    }
                }
            }
            return $this->renderJson(['activity'=>$activity,'activity_attr'=>$activity_attr,'goods_id'=>$activity_id],"返回成功",ConstantService::$response_success);
        }
    }
    /*
     * 活动修改接口
     * */
    public function actionUpdataindex(){


        if ($this->isPost()){

            $activity_id=$this->post('id');
            //活动名称是否以存在
            $activity_del=Activity::find();
            $activity_del->andWhere(['!=','id',$this->post('id')]);
            $activity_del->andWhere(['activity_name'=>$this->post('activity_name')]);
            $activity_del->andWhere(['isdel'=>1]);
            $activity_name=$activity_del->asArray()->one();
            $avtivity_attr = json_decode($this->post("activity_attr"),true);
            if (empty($avtivity_attr)){
                return $this->renderJson([],'请选择活动商品规格',ConstantService::$response_fail);
            }
            //添加活动的时间有效性
            if (strtotime($this->post('begin_time'). ' 00:00:00') >= strtotime($this->post('end_time'). ' 23:59:59')){
                return $this->renderJson([],'结束的时间需大于开始时间',ConstantService::$response_fail);
            }
            //判断活动库存
            //前端传来的商品属性id
            $goods_attr_id=array_column($avtivity_attr,'goods_attr_id');
            $goods_attr_data=GoogsAttr::find()->select(['id','inventory'])->where(['in','id',$goods_attr_id])->asArray()->all();
            foreach ($avtivity_attr as $v){
                foreach ($goods_attr_data as $gd){
                    if ($v['goods_attr_id'] == $gd['id']){
                        if (trim($gd['inventory']) <  trim($v['inventory'])){
                            return $this->renderJson([],'活动库存大于商品库存，请重新填写',ConstantService::$response_fail);
                        }
                    }
                }
            }

            $activity=Activity::find()->where(['id'=>$activity_id])->one();
            $activity->setAttributes([
                'activity_name'=> $this->post('activity_name') ,
                'activity_num'=>$this->post('activity_num') ,
                'begin_time'=>strtotime($this->post('begin_time'). ' 00:00:00') ,
                'end_time'=>strtotime($this->post('end_time'). ' 23:59:59') ,
                'status'=>0 ,
            ]);
            $save=$activity->save();

            if ($save){
                //获取前端传过来的属性值
                foreach ($avtivity_attr as $value) {

                    // if (!empty($value['activity_attr_id'])) {
                        $activityAttr_one = ActivityAttr::find()->where(['id' => $value['id']])->one();
                        $activityAttr_one['attr_value'] = $value['attr_value'];
                        $activityAttr_one['attr_img'] = $value['attr_img'];
                        $activityAttr_one['original_price'] = $value['original_price'];
                        $activityAttr_one['one_price'] = $value['one_price'];
                        $activityAttr_one['discount_price'] = $value['discount_price'];
                        $activityAttr_one['inventory'] = $value['inventory'];
                        $activityAttr_one['goods_attr_id'] = $value['goods_attr_id'];
                        $activityAttr_one->save();

//                     } else {
// //                            echo 111;exit();
//                         $activityAttr=new ActivityAttr();
//                         $activityAttr->setAttributes([
//                             'activity_id'=>$activity_id,
//                             'shop_id'=>$this->shop['id'],
//                             'goods_id'=>$this->post('goods_id'),
//                             'attr_value' => $value['attr_value'],
//                             'attr_img' => $value['attr_img'],
//                             'original_price' => $value['original_price'],
//                             'one_price' => $value['one_price'],
//                             'discount_price' => $value['discount_price'],
//                             'inventory' => $value['inventory'],
//                             'goods_attr_id' => $value['goods_attr_id']
//                         ]);
//                         $activityAttr->save();
//                     }
                }
                return $this->renderJson([],"修改成功",ConstantService::$response_success);

            }else{
                return $this->renderJson([],'活动主表修改失败',ConstantService::$response_fail);
            }
        }else{
            return $this->renderJson([],'非ajax提交',ConstantService::$response_fail);
        }
    }
    /*
     * 删除活动
     * */
    public function actionDel(){
        if ($this->isPost()){
            $id=$this->post('id');
            $re= Activity::findOne($id)->delete();
            if ($re){
                return $this->renderJson([],'删除成功',ConstantService::$response_success);
            }else{
                return $this->renderJson([],'删除失败',ConstantService::$response_fail);
            }
        }

    }



    /*
     * 加载添加活动提交接口
     * */
    public function actionAdd(){
        $activity= new Activity();
        if ($this->isPost()){
            $goodsattrdatas = json_decode($this->post('avtivity_attr'),true);
            if (empty($goodsattrdatas)){
                return $this->renderJson([],'请选择活动商品规格',ConstantService::$response_fail);
            }
            if (strtotime($this->post('begin_time'). ' 00:00:00') >= strtotime($this->post('end_time'). ' 23:59:59')){
                return $this->renderJson([],'结束的时间需大于开始时间',ConstantService::$response_fail);
            }

            // 判断活动名称是否与已添加的一样
            $activity_name=Activity::find()->where(['activity_name'=>$this->post('activity_name'),'isdel'=>1])->asArray()->all();
            foreach ($activity_name as $ac_name){
                if ($this->post('activity_name')== $ac_name['activity_name']){
                    return $this->renderJson([],'此活动名称已存在，请重新填写',ConstantService::$response_fail);
                }
            }

            //前端传来的商品属性
            $goods_attr_id=array_column($goodsattrdatas,'goods_attr_id');

            $goods_attr_data=GoogsAttr::find()->select(['id','inventory'])->where(['in','id',$goods_attr_id])->asArray()->all();

            foreach ($goodsattrdatas as $v){
                foreach ($goods_attr_data as $gd){

                    if ($v['goods_attr_id'] == $gd['id']){
                        if (trim($gd['inventory']) < trim($v['inventory'])){
                            return $this->renderJson([],'活动库存大于商品库存，请重新填写',ConstantService::$response_fail);
                        }
                    }
                }

            }

            //添加活动表
            $activity->setAttributes([
                'shop_id'=> empty($this->shop['id'])?1:$this->shop['id'],
                'goods_id'=> $this->post('goods_id') ,
                'activity_name'=> $this->post('activity_name') ,
                'activity_num'=>$this->post('activity_num') ,
                'creat_time'=>time(),
                'begin_time'=>strtotime($this->post('begin_time'). ' 00:00:00') ,
                'end_time'=>strtotime($this->post('end_time'). ' 23:59:59') ,
                'status'=>0
            ]);
            $save_activity=$activity->save();
            if($save_activity){
                //刚才插入数据的id
                $activity_id=\Yii::$app->db->getLastInsertID();
                //属性表的添加
                //获取前端传过来的属性值
                if ($goodsattrdatas){
                    foreach($goodsattrdatas as &$attributes)
                    {
                        $attributes['activity_id']=$activity_id;
                        $attributes['create_at']=time();
                        $attributes['goods_id']=$this->post('goods_id');
                        $attributes['shop_id']=empty($this->shop['id'])?1:$this->shop['id'];
                    }
                     $sql = ActivityAttr::getDb()->createCommand()->batchInsert('activity_attr',
                         ['attr_value', 'attr_img','one_price','original_price','discount_price','inventory','goods_attr_id','activity_id','create_at','goods_id','shop_id'],
                         $goodsattrdatas)->execute();
                    return $this->renderJson([],"添加成功",ConstantService::$response_success);
                }else{
                    return $this->renderJson([],'请添加商品属性后再添加活动',ConstantService::$response_fail);
                }
            }else{
                return $this->renderJson([],'活动主表添加失败',ConstantService::$response_fail);
            }
        }
    }

    /*
     * 商家添加活动__商品列表和搜索商品
     * */
    public function actionAddSelect(){
            $shop_id=$this->shop['id'];
            //得到商家在活动中和被删除的活动
            $ac=Activity::find();
//            $ac->andWhere(['shop_id'=>$shop_id]);
            $ac->orWhere(['status'=>1]);
            $ac->orWhere(['isdel'=>1]);
            $activity_data_id=$ac->select('goods_id')->asArray()->all();
            $goods_id_ac=array_column($activity_data_id,"goods_id");
            $goods_data_id=Googs::find()->where(['shop_id'=>$shop_id])->asArray()->all();
            //取商家未进行中活动的id
            $goods_id_gd=array_column($goods_data_id,'id');
            $goods_id=array_diff($goods_id_gd,$goods_id_ac);
            //查出还可以参加活动的商品
            $goods_data1=Googs::find();
            $goods_data1->andWhere(['in','id',$goods_id]);
            //搜索的商品名称
            $goods_name=$this->post('goods_name');
            if (!empty($goods_name)){
                $goods_data1->andWhere(['like','googs_name',$goods_name]);
            }
            $goods_data=$goods_data1->asArray()->all();
//            return $this->render('add',['datas'=>$goods_data]);
//        $shop_id = 1;
//        $query = Googs::find();
//            //搜索的商品名称
//        $type = $_REQUEST['status'];
//        if($type == 1) {
//            $goods_name = $_REQUEST['goods_name'];
//            if (!empty($goods_name)) {
//                $query->andWhere(['like', 'googs_name', $goods_name]);
//            }
//        }
//        $query->andWhere(['shop_id'=>$shop_id]);
//        $goods_data = $query->asArray()->all();
        return $this->renderJson(['goods_data'=>$goods_data],"搜索成功",ConstantService::$response_success);
    }

    /*
     * 商家里的商品属性
     * */
    public function  actionAddsku(){
    //点击商品时的商品id
    // if($this->isPost()){
        $goods_id=$_REQUEST['id'];
        $goods_attr=GoogsAttr::find()->where(['googs_id'=>$goods_id])->asArray()->all();

        foreach ($goods_attr as $key=>$val){
            $goods_attr[$key]['attr_img']=GlobalUrlService::buildCdnUrl($val['attr_img']);

        }
        if ($goods_attr){
            return $this->renderJson(['goods_attr'=>$goods_attr],"获取成功",ConstantService::$response_success);
        }else{
            return $this->renderJson([],'获取失败',ConstantService::$response_fail);
        }
    // }
}

    /*
     * 活动二维码
     * */
    public function actionAttrcode(){
        if ($this->isPost()){
            $activity_id=$this->post('id');
            $activity=Activity::find()->where(['id'=>$activity_id])->one();
            if (empty($activity['activity_code'])){
                $qrcode=WechatService::getWechatQrcode($activity_id,"");
                if($qrcode===false){
                    return $this->renderJson([],'获取失败',ConstantService::$response_fail);
                }else{
                    $activity["activity_code"]=$qrcode;
                    $activity->save();
                    $cdnUrl=GlobalUrlService::buildCdnUrl($qrcode);
                    return $this->renderJson(['cdnUrl'=>$cdnUrl],"获取成功",ConstantService::$response_success);
                }
            }else{
                $path=$activity["activity_code"];
                $cdnUrl=GlobalUrlService::buildCdnUrl("$path");
                return $this->renderJson(['cdnUrl'=>$cdnUrl],"获取成功",ConstantService::$response_success);
            }
        }
    }


}